package com.example.managemyself.viewmodel;

import android.app.Application;
import android.os.CountDownTimer;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.Date;

import com.example.managemyself.data.model.PomodoroSession;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.util.NotificationHelper;

/**
 * 番茄钟ViewModel，处理番茄钟相关的UI逻辑
 */
public class PomodoroViewModel extends AndroidViewModel {
    
    // 默认工作时间（25分钟）
    private static final long DEFAULT_WORK_TIME = 25 * 60 * 1000;
    // 默认休息时间（5分钟）
    private static final long DEFAULT_BREAK_TIME = 5 * 60 * 1000;
    
    // 番茄钟状态
    public enum TimerState {
        IDLE,       // 空闲
        WORKING,    // 工作中
        PAUSED,     // 暂停
        BREAKING,   // 休息中
        COMPLETED   // 完成
    }
    
    private CountDownTimer timer;
    private final MutableLiveData<Long> timeLeftInMillis = new MutableLiveData<>();
    private final MutableLiveData<TimerState> timerState = new MutableLiveData<>();
    private final MutableLiveData<Integer> completedPomodoros = new MutableLiveData<>();
    private final MutableLiveData<PomodoroSession> currentSession = new MutableLiveData<>();
    private final MutableLiveData<Task> associatedTask = new MutableLiveData<>();
    
    private long workTimeInMillis = DEFAULT_WORK_TIME;
    private long breakTimeInMillis = DEFAULT_BREAK_TIME;
    private Application application;
    
    public PomodoroViewModel(Application application) {
        super(application);
        this.application = application;
        timeLeftInMillis.setValue(workTimeInMillis);
        timerState.setValue(TimerState.IDLE);
        completedPomodoros.setValue(0);
    }
    
    // 开始番茄钟
    public void startTimer() {
        TimerState currentState = timerState.getValue();
        
        if (currentState == TimerState.IDLE || currentState == TimerState.COMPLETED) {
            // 开始新的工作时间
            startWorkTime();
        } else if (currentState == TimerState.PAUSED) {
            // 继续计时
            resumeTimer();
        }
    }
    
    // 暂停番茄钟
    public void pauseTimer() {
        if (timer != null) {
            timer.cancel();
        }
        timerState.setValue(TimerState.PAUSED);
    }
    
    // 停止番茄钟
    public void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
        timerState.setValue(TimerState.IDLE);
        timeLeftInMillis.setValue(workTimeInMillis);
    }
    
    // 开始工作时间
    private void startWorkTime() {
        timerState.setValue(TimerState.WORKING);
        timeLeftInMillis.setValue(workTimeInMillis);
        
        // 创建并启动计时器
        timer = new CountDownTimer(workTimeInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis.setValue(millisUntilFinished);
            }
            
            @Override
            public void onFinish() {
                // 工作时间结束，开始休息时间
                timerState.setValue(TimerState.BREAKING);
                timeLeftInMillis.setValue(breakTimeInMillis);
                
                // 增加已完成的番茄钟数量
                Integer completed = completedPomodoros.getValue();
                if (completed != null) {
                    completedPomodoros.setValue(completed + 1);
                }
                
                // 显示工作结束通知
                NotificationHelper.showPomodoroNotification(
                        application,
                        "工作时间结束",
                        "恭喜完成一个番茄钟工作时间！现在开始休息吧。"
                );
                
                // 开始休息时间
                startBreakTime();
            }
        }.start();
    }
    
    // 开始休息时间
    private void startBreakTime() {
        timerState.setValue(TimerState.BREAKING);
        
        // 创建并启动计时器
        timer = new CountDownTimer(breakTimeInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis.setValue(millisUntilFinished);
            }
            
            @Override
            public void onFinish() {
                // 休息时间结束
                timerState.setValue(TimerState.COMPLETED);
                timeLeftInMillis.setValue(0L);
                
                // 显示休息结束通知
                NotificationHelper.showPomodoroNotification(
                        application,
                        "休息时间结束",
                        "休息结束了，准备开始新的番茄钟吧！"
                );
            }
        }.start();
    }
    
    // 继续计时
    private void resumeTimer() {
        TimerState currentState = timerState.getValue();
        Long remainingTime = timeLeftInMillis.getValue();
        
        if (currentState == null || remainingTime == null) {
            return;
        }
        
        if (currentState == TimerState.WORKING) {
            timerState.setValue(TimerState.WORKING);
        } else if (currentState == TimerState.BREAKING) {
            timerState.setValue(TimerState.BREAKING);
        } else {
            return;
        }
        
        // 创建并启动计时器
        timer = new CountDownTimer(remainingTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis.setValue(millisUntilFinished);
            }
            
            @Override
            public void onFinish() {
                if (timerState.getValue() == TimerState.WORKING) {
                    // 工作时间结束，开始休息时间
                    timerState.setValue(TimerState.BREAKING);
                    timeLeftInMillis.setValue(breakTimeInMillis);
                    
                    // 增加已完成的番茄钟数量
                    Integer completed = completedPomodoros.getValue();
                    if (completed != null) {
                        completedPomodoros.setValue(completed + 1);
                    }
                    
                    // 显示工作结束通知
                    NotificationHelper.showPomodoroNotification(
                            application,
                            "工作时间结束",
                            "恭喜完成一个番茄钟工作时间！现在开始休息吧。"
                    );
                    
                    // 开始休息时间
                    startBreakTime();
                } else {
                    // 休息时间结束
                    timerState.setValue(TimerState.COMPLETED);
                    timeLeftInMillis.setValue(0L);
                    
                    // 显示休息结束通知
                    NotificationHelper.showPomodoroNotification(
                            application,
                            "休息时间结束",
                            "休息结束了，准备开始新的番茄钟吧！"
                    );
                }
            }
        }.start();
    }
    
    // 设置工作时间
    public void setWorkTimeInMinutes(int minutes) {
        if (minutes > 0) {
            this.workTimeInMillis = minutes * 60 * 1000L;
            if (timerState.getValue() == TimerState.IDLE) {
                timeLeftInMillis.setValue(workTimeInMillis);
            }
        }
    }
    
    // 设置休息时间
    public void setBreakTimeInMinutes(int minutes) {
        if (minutes > 0) {
            this.breakTimeInMillis = minutes * 60 * 1000L;
        }
    }
    
    // 获取剩余时间
    public LiveData<Long> getTimeLeftInMillis() {
        return timeLeftInMillis;
    }
    
    // 获取计时器状态
    public LiveData<TimerState> getTimerState() {
        return timerState;
    }
    
    // 获取已完成的番茄钟数量
    public LiveData<Integer> getCompletedPomodoros() {
        return completedPomodoros;
    }
    
    // 获取当前会话
    public LiveData<PomodoroSession> getCurrentSession() {
        return currentSession;
    }
    
    // 获取关联任务
    public LiveData<Task> getAssociatedTask() {
        return associatedTask;
    }
    
    // 设置关联任务
    public void setAssociatedTask(Task task) {
        associatedTask.setValue(task);
    }
    
    // 格式化时间
    public String formatTime(long timeInMillis) {
        int minutes = (int) (timeInMillis / 1000) / 60;
        int seconds = (int) (timeInMillis / 1000) % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
    
    public int getProgress() {
        if (timeLeftInMillis.getValue() == null || timerState.getValue() == null) {
            return 100;
        }

        long totalTime;
        TimerState state = timerState.getValue();

        if (state == TimerState.WORKING || (state == TimerState.PAUSED && timeLeftInMillis.getValue() > breakTimeInMillis)) {
            totalTime = workTimeInMillis;
        } else if (state == TimerState.BREAKING || (state == TimerState.PAUSED && timeLeftInMillis.getValue() <= breakTimeInMillis)) {
            totalTime = breakTimeInMillis;
        } else {
            return 100;
        }

        if (totalTime == 0) return 100;

        return (int) ((double) timeLeftInMillis.getValue() / totalTime * 100);
    }
    
    @Override
    protected void onCleared() {
        super.onCleared();
        if (timer != null) {
            timer.cancel();
        }
    }
}
